(:
  A procedure that builds a display file from a xml transcription file
  (made by saving an excel file in xml using microsoft excel)
  This file is the first parameter of the script

  For some reasons, the dates in the excel file are incorrect, so the script just extracts
  the time, then adds an offset passed as the second parameter of the script
  (a number, expressed in miliseconds since 1/1/1970)

  An example of use :

    task.sh transcriptXML2Display.xq transcriptionAnna-feuilleDeCalcul3.xml 1166547714996  > dispAnna.xml

  Authors : Steven Collins, J.J. Girardot
:)

import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;

declare namespace ss = "urn:schemas-microsoft-com:office:spreadsheet" ;

declare variable $deltatime := 
   if ($arguments[2] castable as xs:integer) then
       $arguments[2] cast as xs:integer
   else
       xs:integer(0) ;

(: Create missing empty Cell elements for Rows :)
declare function local:mkcl($cl as element()*, $nu as xs:integer) as element()*
{
    if (fn:empty($cl)) then
      ()
    else
      if ($cl[1]/@ss:Index) then
         if (($cl[1]/@ss:Index cast as xs:integer) eq $nu) then
             ($cl[1],local:mkcl($cl[fn:position()>1], 1+$nu))
         else
             (<ss:Cell/>, local:mkcl($cl, 1+$nu))
      else
         ($cl[1],local:mkcl($cl[fn:position()>1], 1+$nu))
} ;

(:
  Convert a "date" - possibly wrong - to an Unix integer
   We imagine the strings is expressed as a "standard" XSchema date,
   CCYY-MM-DDTHH:MM:SS.SSS
   and just get the hour:minute:second part, then add the offset.
:)
declare function local:unixdate($ds as xs:string) as xs:integer
{
   $deltatime + 1000 * (
   if (string-length($ds) ge 19) then
       3600 * xs:integer(fn:substring($ds, 12, 2)) +
       60 * xs:integer(fn:substring($ds, 15, 2)) +
       xs:integer(fn:substring($ds, 18, 2))
   else
       xs:integer(0)
   )
} ;

<display>{
let $inputFile := $arguments[1]
let $table := doc($inputFile)//ss:Table/ss:Row
for $row at $position in $table
let $cells := local:mkcl($row/ss:Cell, 1)
return
  <item>{
     <info name="type">transcription</info>,
     <info name="user">{ $cells[1]/ss:Data/text() }</info>,
     <info name="time"><time><date>{
           xs:string(local:unixdate($cells[2]/ss:Data/text()))
     }</date></time></info>,
     <info name="comment">{ $cells[3]/ss:Data/text() }</info>,
     <info name="content"><text color="blue">{ $cells[4]/ss:Data/text() }</text></info>
  }</item>
}</display>
